import React, { useState } from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { UserIcon } from 'lucide-react'
// 导入之前创建的Upload组件
import Upload from '@/components/Upload'

interface FileStatus {
  id: string
  file: File
  progress: number
  status: 'pending' | 'uploading' | 'success' | 'error'
  error?: string
  url?: string
}

interface AvatarUploadDialogProps {
  /**
   * 当前头像URL
   */
  currentAvatarUrl?: string
  /**
   * 头像上传成功回调
   */
  onAvatarChange?: (url: string) => void
}

const AvatarUploadDialog: React.FC<AvatarUploadDialogProps> = ({
  currentAvatarUrl,
  onAvatarChange,
}) => {
  const [open, setOpen] = useState(false)
  const [previewUrl, setPreviewUrl] = useState<string>(currentAvatarUrl || '')
  const [uploading, setUploading] = useState(false)

  // 处理文件选择和预览
  const handleFileSelect = (files: FileStatus[]) => {
    const file = files[0]
    if (file && file.file) {
      // 创建本地预览URL
      const objectUrl = URL.createObjectURL(file.file)
      setPreviewUrl(objectUrl)
    }
  }

  // 处理上传确认
  const handleConfirm = async () => {
    if (!previewUrl) return

    try {
      setUploading(true)
      // 这里添加实际的上传逻辑
      // const response = await uploadToServer(previewUrl)
      // const finalUrl = response.url

      // 模拟上传延迟
      await new Promise((resolve) => setTimeout(resolve, 1000))

      onAvatarChange?.(previewUrl)
      setOpen(false)
    } catch (error) {
      console.error('Upload failed:', error)
    } finally {
      setUploading(false)
    }
  }

  // 处理对话框关闭
  const handleClose = () => {
    setOpen(false)
    // 如果没有确认上传，恢复到原来的头像
    setPreviewUrl(currentAvatarUrl || '')
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <div className="relative m-auto cursor-pointer group">
          <Avatar className="w-24 h-24">
            <AvatarImage src={currentAvatarUrl} />
            <AvatarFallback>
              <UserIcon className="w-12 h-12 text-gray-400" />
            </AvatarFallback>
          </Avatar>
          <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity rounded-full">
            <span className="text-white text-xs">更换头像</span>
          </div>
        </div>
      </DialogTrigger>

      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>更换头像</DialogTitle>
          <DialogDescription>请上传一张清晰的头像图片</DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          <div className="flex items-center justify-center">
            <Avatar className="w-32 h-32">
              <AvatarImage src={previewUrl} />
              <AvatarFallback>
                <UserIcon className="w-16 h-16 text-gray-400" />
              </AvatarFallback>
            </Avatar>
          </div>

          <Upload
            accept="image/*"
            maxSize={5 * 1024 * 1024}
            multiple={false}
            showFileList={false}
            hint="支持 jpg、png 格式，大小 5MB 以内"
            onChange={handleFileSelect}
          />
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>
            取消
          </Button>
          <Button onClick={handleConfirm} disabled={!previewUrl || uploading}>
            {uploading ? '上传中...' : '确定'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

export default AvatarUploadDialog
